package tools

import java.io.{File, FileInputStream}
import java.nio.file.Files

import config.{Global, MyFile}
import org.apache.commons.io.{FileUtils, IOUtils}
import play.api.data.Form
import play.api.data.FormBinding.Implicits._
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc.{MultipartFormData, Request}
import play.shaded.oauth.org.apache.commons.codec.binary.Base64
import utils.ExecCommand


object Lastz extends MyFile{

  case class LastzData(targetText: Option[String], queryText: Option[String])

  val lastzForm: Form[LastzData] = Form(
    mapping(
      "targetText" -> optional(text),
      "queryText" -> optional(text)
    )(LastzData.apply)(LastzData.unapply)
  )


  def lastz(implicit request: Request[MultipartFormData[File]]) = {
    var valid = "true"
    var msg = ""
    var base641 = ""
    var base642 = ""
    var axtString = ""
    try {

      val data = lastzForm.bindFromRequest.get
      val tmpDir = Files.createTempDirectory("tmpDir").toString
      val targetFile = new File(tmpDir, "target.fa")
      data.targetText.map { targetText =>
        FileUtils.writeStringToFile(targetFile, targetText)
      }.getOrElse {
        val file = request.body.file("targetFile").get
        file.ref.moveToFile(targetFile)
      }
      val queryFile = new File(tmpDir, "query.fa")
      data.queryText.map { queryText =>
        FileUtils.writeStringToFile(queryFile, queryText)
      }.getOrElse {
        val file = request.body.file("queryFile").get
        file.ref.moveToFile(queryFile)
      }
      println(tmpDir)
      val command = s"perl ${Global.path}/tools/mummer/SV_finder_2.2.1/bin/SV_finder.pl $targetFile $queryFile --prefix data --tfix target --qfix query --nocomp --outdir output --locate"
      val execCommand = new ExecCommand()
      execCommand.exect(Array(command), tmpDir)
      if (execCommand.isSuccess) {
         base641 = getBase64Str(s"$tmpDir/output/02.Lastz/Target-Query.parallel.png".toFile)
         base642 = getBase64Str(s"$tmpDir/output/02.Lastz/Target-Query.xoy.png".toFile)
         axtString = s"$tmpDir/output/02.Lastz/all.axt".readFileToString
      } else {
        valid = "false";msg = execCommand.getErrStr
      }
      tmpDir.delete
    } catch {
      case e: Exception => valid = "false"; msg = e.getMessage
    }

    if(Global.isWindow){
      valid = "true"
      base641 = getBase64Str(s"${Global.testResult}/lastz/Target-Query.parallel.png".toFile)
      base642 = getBase64Str(s"${Global.testResult}/lastz/Target-Query.xoy.png".toFile)
      axtString = s"${Global.testResult}/lastz/all.axt".readFileToString
    }

    Json.obj("valid"->valid,"msg"->msg,"base641" -> base641, "base642" -> base642, "axtString" -> axtString)
  }

  def getBase64Str(imageFile: File): String = {
    val inputStream = new FileInputStream(imageFile)
    val bytes = IOUtils.toByteArray(inputStream)
    val bytes64 = Base64.encodeBase64(bytes)
    inputStream.close()
    new String(bytes64)
  }
}
